package com.jxs.android.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;

public class InstallHolder {

	public static final String INSTALL_PACKAGE = "com.jxs.android.ges";
	public static final String INSTALL_PACKAGE_APK = "com.jxs.android.ges.apk";
	public static final String INSTALL_PACKAGE_VESION = "1.0.3.1";

	public static boolean retrieveApkFromAssets(Context context, String fileName, String path) {
		boolean bRet = false;

		try {
			File file = new File(path);
			if (file.exists()) {
				return true;
			} else {
				file.createNewFile();
				InputStream is = context.getAssets().open(fileName);
				FileOutputStream fos = new FileOutputStream(file);

				byte[] temp = new byte[1024];
				int i = 0;
				while ((i = is.read(temp)) != -1) {
					fos.write(temp, 0, i);
				}
				fos.flush();
				fos.close();
				is.close();

				bRet = true;
			}

		} catch (IOException e) {
			Builder builder = new Builder(context);
			builder.setMessage(e.getMessage());
			builder.show();
		}

		return bRet;
	}

	/**
	 * 提示用户安装程序
	 */
	public static void showInstallConfirmDialog(final Context context, final String filePath, boolean update) {
		AlertDialog.Builder tDialog = new AlertDialog.Builder(context);
		tDialog.setIcon(android.R.drawable.ic_dialog_alert);
		tDialog.setTitle("软件安装");
		if (update) {
			tDialog.setMessage("版本太低，无法使用,是否升级？");
		} else {
			tDialog.setMessage("未安装该程序，是否安装？");
		}
		tDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				// 修改apk权限
				try {
					String command = "chmod " + "777" + " " + filePath;
					Runtime runtime = Runtime.getRuntime();
					runtime.exec(command);
				} catch (IOException e) {
					e.printStackTrace();
				}
				// install the apk.
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
				context.startActivity(intent);

			}
		});

		tDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
			}
		});

		tDialog.show();
	}
}
